<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入部门编号或名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keyQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading"
              :row-key="getRowKey" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55" :reserve-selection="true">
			</el-table-column>
			<el-table-column type="index" label="序号" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="150"align="center">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="150" align="center">
			</el-table-column>
			<el-table-column prop="dirPath" label="部门路径" width="150" align="center">
			</el-table-column>
			<el-table-column prop="state" label="部门状态" width="150" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: lightseagreen">启用</span>
          <span v-else style="color: crimson">禁用</span>
        </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门经理" width="180" align="center">
			</el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="180" align="center">
			</el-table-column>
			<el-table-column label="操作" width="150" align="center">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="totals"
          :page-sizes="[5, 8, 10]"
          style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加修改对话框-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="部门经理">
            <el-select v-model="saveForm.managerId" placeholder="请选择">
              <el-option
                  v-for="item in managers"
                  :label="item.username"
                  :value="item.id">
                <span style="float: left">{{ item.username }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
              </el-option>
            </el-select>
				</el-form-item>
        <el-form-item label="上级部门">
          <el-cascader
              v-model="saveForm.parentId"
              :options="deptTree"
              :props="{ checkStrictly: true, label: 'name',value:'id' }"
              clearable></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
    watch: {
      saveFormVisible(val) { // 当弹窗打开时
        // 重置表单，清空校验信息
        this.$nextTick(() => {
          //  延时到下一帧才开始，也就是页面刚刚渲染结束！！
          this.$refs.saveForm.clearValidate()
        })
      }
    },
		data() {
			return {
        // 分页相关数据
        currentPage: 1,
        pageSize: 5,
        totals: 0,
        departments: [],
        listLoading: false,
        // 高级查询
        keyword: '',
        // 所有经理
        managers: '',
        // 分页批量选中
        getRowKey(row){
          return row.id;
        },
        // 部门树
        deptTree: [],
        // 批量删除
				sels: [],//列表选中列
				//对话框数据
        title: '',
				saveForm: {
					id: null,
          sn: '',
					name: '',
          state: 1,
          managerId: null,
          parentId: null
				},
				saveFormVisible: false,//新增界面是否显示
				saveLoading: false, // 加载框
				saveFormRules: { // 表单项校验
					sn: [
						{ required: true, message: '请输入部门编号', trigger: 'blur' }
					],
          name: [
            { required: true, message: '请输入部门名称', trigger: 'blur' }
          ]
				},
			}
		},
		methods: {
      //分页查询
      getDepartments() {
        let param = {
          pageSize: this.pageSize,
          currentPage: this.currentPage,
          keyword: this.keyword
        };
        this.listLoading = true;
        this.$http.post("/department", param).then(res=>{
          this.departments = res.data.data
          this.totals = res.data.totals
          this.listLoading = false;
        })
      },
      // 高级查询
      keyQuery(){
        this.currentPage = 1
        this.getDepartments();
      },
      //选择第几页时触发
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.getDepartments();
      },
      //选择每页显示记录条数
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getDepartments();
      },
      //删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.delete("/department/" + row.id).then(res=>{
              if (res.data.success){
                let pageTotal = Math.ceil(this.totals/this.pageSize)
                if (this.currentPage != 1 && this.currentPage == pageTotal && (this.totals - 1)%this.pageSize ==0){
                  this.currentPage = this.currentPage - 1
                }
                this.getDepartments();
              } else {
                this.$message.error("系统繁忙，请稍后重试！【500】")
              }
          }).catch(res=> {
            this.$message.error("系统繁忙，请稍后重试！【400,404,405】")
          })
          this.listLoading = false;
        }).catch(() => { // 取消

        });
      },
      // 选中改变时
      selsChange: function (sels) {
        this.sels = sels.map(obj => obj.id);
      },
      //批量删除
      batchRemove: function () {
        var ids = this.sels
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/department",ids).then(res => {
            this.listLoading = false;
            if(res.data.success){
              //计算总页数
              let totalPage = Math.ceil(this.totals/this.pageSize)
              if(this.currentPage > 1 && this.currentPage==totalPage && (this.totals-this.sels.length)%this.pageSize==0){
                this.currentPage = this.currentPage - 1;
              }
              this.getDepartments();
            }else{
              this.$message.error("系统繁忙，请稍后重试![500]");
            }
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试![400]");
          })
        }).catch(() => {
        });
      },
			//显示编辑界面
			handleEdit: function (index, row) {
        this.title = '编辑'
        this.saveForm = Object.assign({}, row);
        this.getManagers();
        this.getDeptTree();
				this.saveFormVisible = true;
			},
			//显示新增界面
			handleAdd: function () {
        this.title = '添加'
        this.saveForm = { // 重置数据
          id: null,
          sn: '',
          name: '',
          state: 1,
          managerId: null,
          parentId: null
				};
        this.getManagers();
        this.getDeptTree();
        this.saveFormVisible = true;
			},
			//提交按钮
      saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
              let para = Object.assign({},this.saveForm)
              // 判断parentId
              let temp = para.parentId
              if (temp == null || temp.length == 0){ // 顶级部门
                para.parentId = null;
              } else if (temp.length) { // 子部门 获取id
                para.parentId = temp[temp.length-1]
              }
							this.$http.put("/department",para).then(res=>{
                this.saveLoading = false;
                this.saveFormVisible = false;
                if (res.data.success){
                  this.getDepartments()
                  this.$message.success("操作成功！")
                } else {
                  this.$message.error(res.data.message);
                }
              }).catch(res=>{
                this.$message.error("系统繁忙，请稍后重试![400]");
              })
						});
					}
				});
			},
      // 获取所有经理
      getManagers(){
        this.$http.get("/employee").then(res => {
          this.managers = res.data;
        })
      },
      // 获取部门树
      getDeptTree(){
        this.$http.get("/department/deptTree").then(res => {
          this.deptTree = res.data;
        })
      }
		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>